package org.example.coupon.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.core.constant.TokenConstants;
import org.example.core.utils.PageUtils;
import org.example.core.utils.R;
import org.example.coupon.api.OssService;
import org.example.coupon.dao.HomeAdvertiseDao;
import org.example.coupon.entity.HomeAdvertiseEntity;
import org.example.coupon.vo.FrontAdvertiseVo;
import org.example.security.handler.SecurityHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.coupon.service.HomeAdvertiseService;

import java.time.LocalDateTime;
import java.util.List;


@Service("homeAdvertiseService")
public class HomeAdvertiseServiceImpl implements HomeAdvertiseService {

    @Autowired
    private HomeAdvertiseDao homeAdvertiseDao;
    @Autowired
    private OssService ossService;

    // 添加首页广告轮播
    @Override
    public int saveHomeAdvertise(HomeAdvertiseEntity homeAdvertise) {
        String userId = SecurityHandler.getData().get(TokenConstants.USER_ID);
        homeAdvertise.setPublisherId(Long.parseLong(userId));
        return homeAdvertiseDao.addHomeAdvertise(homeAdvertise);
    }

    @Override
    public PageUtils getHomeAdvertiseList(Integer pageNum, Integer pageSize, String name, Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        List<HomeAdvertiseEntity> advertiseEntities = homeAdvertiseDao.getHomeAdvertiseList(name, status);
        return new PageUtils(new PageInfo<>(advertiseEntities));
    }

    // 查询单个广告信息
    @Override
    public HomeAdvertiseEntity getHomeAdvertiseInfo(Long id) {
        return homeAdvertiseDao.getHomeAdvertiseInfo(id);
    }

    @Override
    public int updateAdvertiseInfo(HomeAdvertiseEntity homeAdvertise) {
        return homeAdvertiseDao.updateAdvertiseInfo(homeAdvertise);
    }

    @Override
    public R<?> deletes(List<Long> ids) {
        List<String> urlList = homeAdvertiseDao.urlList(ids);
        // 删除
        if (homeAdvertiseDao.deletes(ids) <= 0){
            return R.error();
        }
        int code = ossService.removes(urlList).getCode();
        if (code != 0){
            return R.error();
        }
        return R.ok();
    }

    @Override
    public List<FrontAdvertiseVo> getHomeFrontAdvertiseList() {
        LocalDateTime nowTime = LocalDateTime.now();
        return homeAdvertiseDao.getHomeFrontAdvertiseList(nowTime, 0);
    }
}